package com.example.demo.service;

import com.example.demo.dao.Alink;
import com.example.demo.util.BookUtil;
import com.example.demo.util.HtmlUtil;
import com.example.demo.util.HttpUtilOpti;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class BookListService {

    /**
     *
     * @param address   页面地址
     * @param listLabel 章节链接标签
     * @return
     * @throws Exception
     */
    public HashMap getListPage(String address, String content, String listLabel) throws Exception {
        org.jsoup.nodes.Document doc = Jsoup.parse(content);
        String hostPrefix = address.substring(0, address.indexOf("com") + 4);

        // 获取小说名称
        String bookName = BookUtil.getBookTitle(content, "h1");

        // 获取简介
        String bookInfo = doc.select("#intro p").text();
        // 获取到包含所有章节链接的节点
        org.jsoup.select.Elements contents = doc.select(listLabel);
        // 新建一个存放章节链接的集合
        List<Alink> lists = new ArrayList<Alink>();
        String temp = "";
        // 遍历所有章节链接
        for (int i = 0; i < contents.size(); i++) {
            Alink alink = new Alink();
            // temp = contents.get(i).html().replaceAll("&lt;", "<");
            // temp = temp.replaceAll("&gt;", ">");
            alink.setText(contents.get(i).text());
            String link = contents.get(i).attr("href");
            alink.setLink(contents.get(i).attr("href"));
            lists.add(alink);
            String chapterPageContent = HttpUtilOpti.get(link);
            String chapterText = HtmlUtil.getHtmlContentByTag(chapterPageContent, "#dashu_text");
            String result = chapterText;
            if(result.length() < 0){
                continue;
            }
        }
        HashMap map = new HashMap<>();
        map.put("bookTitle", bookName);
        map.put("bookInfo", bookInfo);
        map.put("bookList", lists);
        return map;
    }
}
